import { useState, useEffect } from "react";
import {
  getCurrentInstance,
  navigateBack,
  navigateTo,
  showToast,
} from "@tarojs/taro";
import { Button, Image, View, Text } from "@tarojs/components";
import Navbar from "@/components/Navbar";
import "./index.less";
import BusinessConstant from "@/constant/BusinessConstant";
import useIdentity from "@/hooks/useIdentity";
import { Input } from "@nutui/nutui-react-taro";
import systemStore from "@/stores/SystemStore";
import ImageConstant from "@/constant/ImageConstant";
import { IconFont } from "@nutui/icons-react-taro";
import { observer } from "mobx-react-lite";
import authStore from "@/stores/AuthStore";
import AuthConstant from "@/constant/AuthConstant";

const Login = () => {
  const { userLogin, getUserInfo, userRegistry } = useIdentity();
  const $instance = getCurrentInstance();
  const [phone, setPhone] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [checkPassword, setCheckPassword] = useState<string>("");
  const [isRegister, setIsRegister] = useState(false);
  /**
   * 处理获取手机号
   */
  const handleLogin = async () => {
    if (!isRegister) {
      // 登录请求
      await userLogin(phone, password);
      // 获取用户信息
      await getUserInfo();
      // 若参数中传递了execute参数且值为EXECUTE_BACK
      if ($instance.router?.params.execute === BusinessConstant.EXECUTE_BACK) {
        navigateBack();
        return;
      }
      navigateBack();
    } else {
      // 注册请求
      await userRegistry(phone, password, checkPassword);
      setIsRegister(false);
      showToast({
        title: "注册成功",
        icon: "success",
      });
    }
  };

  useEffect(() => {
    // 清除填写的信息
    setPhone("");
    setPassword("");
    setCheckPassword("");
  }, [isRegister]);

  const getIdentityName = () => {
    switch (authStore.identity) {
      case AuthConstant.TENANT:
        return "租客";
      case AuthConstant.LANDLORD:
        return "房东";
      default:
        return "";
    }
  };

  return (
    <Navbar className="login-container">
      <View className="login-bg">
        <IconFont
          name={`${ImageConstant.SERVER_ROOT}/common/home-icon.png`}
          style={{ marginTop: `${systemStore.navbarHeight - 30}px` }}
          className="home-icon"
          onClick={() => navigateTo({ url: "/pages/tabbar/index" })}
        />
        <View className="flex justify-center">
          <Image src={ImageConstant.LOGO} className="logo" mode="widthFix" />
        </View>
        <View className="text">
          <View className="text-wrap1">
            <Text className="text-hello">您好，</Text>
            <Text className="text-identity">{getIdentityName()}</Text>
          </View>
          <View className="text-wrap2">
            <Text className="text-welcome">欢迎使用</Text>
            <Text className="text-name">LTS行间小筑</Text>
          </View>
        </View>
        <View className="form-input-wrap">
          <View className="input-wrap">
            <IconFont
              name={`${ImageConstant.SERVER_ROOT}/common/phone-icon.png`}
              className="icon"
            />
            <Input
              placeholder="请输入手机号"
              value={phone}
              maxLength={11}
              onChange={(val) => setPhone(val)}
              type="number"
              className="input"
            />
          </View>
          <View className="input-wrap">
            <IconFont
              name={`${ImageConstant.SERVER_ROOT}/common/password-icon.png`}
              className="icon"
            />
            <Input
              placeholder="请输入密码"
              value={password}
              onChange={(val) => setPassword(val)}
              type="password"
              className="input"
            />
          </View>
          {isRegister && (
            <View className="input-wrap">
              <IconFont
                name={`${ImageConstant.SERVER_ROOT}/common/password-icon.png`}
                className="icon"
              />
              <Input
                placeholder="请再次输入密码"
                value={checkPassword}
                onChange={(val) => setCheckPassword(val)}
                type="password"
                className="input"
              />
            </View>
          )}
          <Button className="btn" onClick={handleLogin}>
            {isRegister ? "注册" : "登录"}
          </Button>
          {isRegister && (
            <Button className="btn" onClick={() => setIsRegister(false)}>
              返回登录
            </Button>
          )}
        </View>
        {!isRegister && systemStore.systemConfig.registryEntry === 1 && (
          <View className="register">
            新用户？
            <Text
              className="register-entry"
              onClick={() => setIsRegister(true)}
            >
              立即注册
            </Text>
          </View>
        )}
      </View>
    </Navbar>
  );
};

export default observer(Login);
